import React, {useCallback, useState} from 'react';
import {ApiResult} from "@/utils/data";
import {message} from "antd";

/** 编辑组件属性 */
export interface EditProps<T> {
  created: boolean,
  /** 提交操作成功后的提示消息 */
  submitSuccessMessage?: React.ReactNode;
  /** 提交对象 */
  onSave?: (_created: boolean, oldRecord: any, newRecord: any) => Promise<ApiResult>;
}

/** 编辑组件返回值 */
export interface EditOperate<T> {
  /** 表示提交操作是否正在进行中 */
  submitLoading: boolean;
  /** 数据保存函数 */
  save: (oldRecord: any, newRecord: any, callback?: () => void) => void;
}

/** 编辑操作组件 */
function useSave<Model>(props: EditProps<Model>): EditOperate<Model> {
  const {created, submitSuccessMessage = '保存成功', onSave} = props;

  const [submitLoading, setSubmitLoading] = useState(false);

  /** 提交函数  */
  const save = useCallback((oldRecord: Partial<Model> | undefined, newRecord: Model, callback?: () => void) => {
    if (!onSave) return;

    setSubmitLoading(true);
    const record = {...oldRecord, ...newRecord};
    onSave(created, oldRecord, record)?.then(r => {
      setSubmitLoading(false)
      if (r.success) {
        submitSuccessMessage && message.success({content: submitSuccessMessage, duration: 1});
        callback && callback();
      }
    }).catch(() => setSubmitLoading(false));
  }, [created, submitSuccessMessage]);

  return {
    submitLoading,
    save,
  };
}

export default useSave;

